#!/bin/bash

# cjgit - Pull Command
# Update all Cangjie projects with latest changes from remote

# Source common functions
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/cjgit-common.sh"

# Pull command implementation
pull_command() {
    print_info "Starting pull operation across all Cangjie projects..."
    echo
    
    for project in "${PROJECTS[@]}"; do
        print_info "Processing project: $project"
        
        # Check if project directory exists
        if [[ ! -d "$project" ]]; then
            print_error "Project directory '$project' not found!"
            exit 1
        fi
        
        # Check if it's a git repository
        if [[ ! -d "$project/.git" ]]; then
            print_error "'$project' is not a git repository!"
            exit 1
        fi
        
        # Find the correct remote
        remote=$(find_cangjie_remote "$project")
        if [[ -z "$remote" ]]; then
            print_error "No Cangjie remote found in '$project'!"
            exit 1
        fi
        
        print_info "Found remote: $remote"
        
        # Check if remote dev branch exists
        if ! git -C "$project" show-ref --verify --quiet "refs/remotes/$remote/dev"; then
            print_error "Remote branch '$remote/dev' does not exist in '$project'!"
            exit 1
        fi
        
        # Check if remote has changes
        if ! upstream_has_changes "$project" "$remote"; then
            print_info "No changes in remote, skipping '$project'..."
            echo
            continue
        fi
        
        print_info "Remote has changes, proceeding with update..."
        
        # Check for local changes and stash if needed
        local stashed=false
        if has_local_changes "$project"; then
            print_warning "Local changes detected in '$project', stashing..."
            
            if ! git -C "$project" stash; then
                print_error "Failed to stash changes in '$project'!"
                exit 1
            fi
            stashed=true
            print_success "Changes stashed successfully"
        else
            print_info "No local changes to stash in '$project'"
        fi
        
        # Perform rebase with signoff
        print_info "Rebasing onto $remote/dev with signoff..."
        
        if ! git -C "$project" rebase --signoff "$remote/dev"; then
            print_error "Rebase failed in '$project'!"
            print_error "Leaving directory in current state for manual resolution"
            
            # Notify about stashed changes if any
            if [[ "$stashed" == true ]]; then
                print_error "Changes were stashed before the failed rebase"
                print_error "Use 'git stash pop' in '$project' to restore your changes after resolving the rebase"
            fi
            
            exit 1
        fi
        
        print_success "Rebase completed successfully"
        
        # Unstash if we stashed earlier
        if [[ "$stashed" == true ]]; then
            print_info "Applying stashed changes..."
            if ! git -C "$project" stash pop; then
                print_error "Failed to apply stashed changes in '$project'!"
                print_error "Please resolve stash conflicts manually in '$project'"
                exit 1
            fi
            print_success "Stashed changes applied successfully"
        fi
        
        echo
    done
    
    print_success "Pull operation completed across all projects"
}

# Help function for pull command
help_command() {
    echo "Usage: cjgit pull"
    echo
    echo "Update all Cangjie projects with latest changes from remote"
    echo
    echo "This command performs a rebase operation to keep your local branches"
    echo "up to date with the upstream repository."
    echo
    echo "Examples:"
    echo "  cjgit pull                     # Update all projects"
}

# Main execution
if [[ "$1" == "--help" || "$1" == "-h" ]]; then
    help_command
    exit 0
fi

pull_command